package com.me.customerdemo.controller;

import com.github.pagehelper.PageInfo;
import com.me.customerdemo.pojo.BaseDict;
import com.me.customerdemo.service.BaseDictService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 客户管理模块控制器
 */
@Controller
public class BaseDictController {


    private static Logger logger= LoggerFactory.getLogger(BaseDictController.class);
    //Autowired注解所标注的成员变量
   @Autowired
    BaseDictService basedictService;

    @GetMapping("/basedict/basedict_add")
    public ModelAndView basedictAddView() {
        final ModelAndView mav = new ModelAndView("basedict/basedict_add");
        return mav;
    }

    @GetMapping("/basedict/basedict_list")
    public ModelAndView basedictListView(
            @RequestParam(name="pageNum", required = true,defaultValue = "1") int pageNum,
            @RequestParam(name="pageSize", required = true,defaultValue = "5") int pageSize,
            @RequestParam(name="keyword",required = false) String keyword
    ) {

        final ModelAndView mav = new ModelAndView("basedict/basedict_list");
       // 分页查询数据

//       PageInfo<Basedict> page=basedictService.findAll(pageNum,pageSize);
        PageInfo<BaseDict> page=basedictService.findByKeyword(pageNum, pageSize, keyword);
        mav.addObject("page",page);
        mav.addObject("keyword",keyword);
        return mav;
    }

    @GetMapping("/basedict/basedict_modify")
    public ModelAndView basedictModifyView(
            @RequestParam(name = "id",required = true) int id
    ){
        ModelAndView mav=new ModelAndView("basedict/basedict_modify");
        //查询要编辑的客户的信息，并将它装如到环境中。
        BaseDict basedict=basedictService.findById(id);
        mav.addObject("basedict",basedict);
        return mav;
    }

    @PostMapping("/basedict/basedict_add")
    //@Validated注解标注的命令对象，表示该对象中的属性必须按照已定义的规则进行验证
    // BindingResult参数封装了有关验证的信息，重点式包含了哪些字段出错，以有相应的错误信息
    public ModelAndView basedictAdd(@Validated BaseDict basedict, BindingResult bindingResult){
        ModelAndView mav = new ModelAndView("redirect:/basedict/basedict_add");
        // 验证Basedict实例中的每一个属性字段值是否符合规则
        // 如果符合规则 则保存数据 返回正常的视图
        // 如果不符合规则 则返回错误信息添加视图

        // 1. 编写验证代码
        // 2. 给视图环境添加错误信息及错误的字段
        // 3. 返回添加的页面 同时还要在页面上显示用户刚填写的内容

        Map<String,String> errors = new HashMap<>();
        if (bindingResult.hasErrors()){
            // 取出错误对象
            final List<FieldError> fieldErrors = bindingResult.getFieldErrors();
            // 取出发生错误的字段名称及相应的错误信息 放入到映射集合中 用于发送到视图环境
            for (FieldError error : fieldErrors){
                // 从错误对象中取出相应的字段名称作为键 对应的错误信息作为值 放入到映射集合中
                errors.put(error.getField(),error.getDefaultMessage());
            }
            mav.addObject("errors",errors);
            mav.addObject("basedict",basedict);
            mav.setViewName("basedict/basedict_add");
        }else{
            boolean result = basedictService.apply(basedict);
            if (result){
                logger.info("管理员***，成功添加一个新客户 - " + basedict);
            }else {
                logger.error("管理员***，新增客户信息失败 - " + basedict);
            }
        }

        // 调用服务层方法来保存数据
//        basedictService.apply(basedict);
        return mav;
    }

    @PostMapping("/basedict/basedict_modify")
    public ModelAndView basedictModify(
            BaseDict basedict,
            @RequestParam(name = "pageSize",required = false,defaultValue = "5") int pageSize,
            @RequestParam(name = "pageNum",required = false,defaultValue = "1") int pageNum,
            @RequestParam(name = "keyword",required = false) String keyword

    ) throws UnsupportedEncodingException {
        String redirectUrl = "redirect:/basedict/basedict_list?pageSize=" +
                pageSize + "&pageNum=" + pageNum +
                "&keyword=" + (keyword == null? "" : URLEncoder.encode(keyword,"utf-8"));
        ModelAndView mav = new ModelAndView(redirectUrl);
        // 调用服务层 保存客户信息
        boolean result = basedictService.modify(basedict);
        return mav;
    }

      @GetMapping("/basedict/basedict_remove")
    public ModelAndView basedictRemove(
            @RequestParam(name = "id",required = true) int id,
              @RequestParam(name = "pageSize",required = false,defaultValue = "5") int pageSize,
              @RequestParam(name = "pageNum",required = false,defaultValue = "1") int pageNum,
              @RequestParam(name = "keyword",required = false) String keyword
      ) throws UnsupportedEncodingException {
          String redirectUrl = "redirect:/basedict/basedict_list?pageSize=" + pageSize +
                  "&pageNum=" +pageNum +
                  "&keyword=" + (keyword == null? "": URLEncoder.encode(keyword,"utf-8"));
          ModelAndView mav=new ModelAndView(redirectUrl);

          boolean result= basedictService.removeById(id);

          if(result){
              logger.info("管理员****,删除一个新客户 - id" + id);
          }else{
              logger.error("管理员***","新客户信息失败 ~ id" + id);
          }


          return mav;
      }


}